#include "mytableview.h"
#include "mytablemodel.h"
#include <QHeaderView>
#include <QPainter>
MyTableView::MyTableView(QWidget *parent)
    : QTableView{parent}
    , m_pMyTableModel(nullptr)
    , m_lhoveredRow(-1)
{
    m_pMyTableModel = new MytableModel(this);
    stFileInfo*  fileinfo = new stFileInfo();
    fileinfo->m_bChecked = false;
    fileinfo->fileName = "word文档";
    this->horizontalHeader()->setSectionsMovable(true);  // 启用列拖拽
    //this->horizontalHeader()->setSectionResizingMode(QHeaderView::Interactive); // 启用列宽调整
    //setSelectionBehavior(QAbstractItemView::SelectItems); // 选择单元格时，允许选择整个项
    //this->horizontalHeader()->setSectionMoveable(true);
    m_pMyTableModel->addData(fileinfo);
    //this->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);
    this->setModel(m_pMyTableModel);
    this->setFocusPolicy(Qt::StrongFocus);
    this->setColumnWidth(0, 20);
    connect(this, SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)));
    setMouseTracking(true);
}

void MyTableView::onTableClicked(const QModelIndex & index)
{
    if(index.column() == 0)
    {
        bool checked = index.model()->data(index, Qt::CheckStateRole).toBool();
        m_pMyTableModel->setdata(index, !checked, Qt::CheckStateRole);
    }
}

void MyTableView::mouseMoveEvent(QMouseEvent *event)
{
    // 获取鼠标悬浮的位置
    QModelIndex index = indexAt(event->pos());
    // 如果鼠标悬浮的行发生变化，则更新
    if (index.isValid() && index.row() != m_lhoveredRow)
    {
        m_lhoveredRow = index.row();
        update();  // 请求重新绘制
    }
}

void MyTableView::paintEvent(QPaintEvent *event)
{
    QTableView::paintEvent(event);  // 先绘制默认的视图

    // 绘制悬浮行的背景色
    if (m_lhoveredRow != -1) {
        QPainter painter(viewport());
        QStyleOptionViewItem option;
        option.initFrom(this);
        // 获取悬浮行的矩形区域
        QRect rowRect = visualRect(model()->index(m_lhoveredRow, 0));
        qDebug() << rowRect.width();
        painter.fillRect(rowRect, QColor(200, 200, 255));  // 背景色
    }
}

